from telethon import TelegramClient, utils, errors
from telethon.sessions import StringSession
import asyncio
import datetime

api_id = ""
api_hash = ""
phone = ""
password = ""  # 二次验证的密码，如果没有，为空即可
"""
PROXY_TYPE_SOCKS4 = SOCKS4 = 1
PROXY_TYPE_SOCKS5 = SOCKS5 = 2
PROXY_TYPE_HTTP = HTTP = 3
"""
# 目前我使用的是socket5 的代理
p = (2, "127.0.0.1", 1080)
# 如果是多线程采集的情况下，需要指定事件循环，在单线程的情况，可以不要loop参数
loop = asyncio.new_event_loop()

session = StringSession("xxx")
client = TelegramClient(session, api_id, api_hash,
                        proxy=p, loop=loop,
                        auto_reconnect=True,
                        )
client.start(phone=phone, password=password)
print(client.get_me())

username = "群组｜频道 的username或者id"
min_id = 0  # 开启的消息id
limit = 1000  # 检索的消息数量


# 异步消息处理
async def receive_msg():
    messages = client.iter_messages(username, min_id=min_id, reverse=True, limit=limit)
    # 进行消息处理
    for message in messages:
        print(message)


async def dow():
    dialog = await client.get_entity("fordarknetspiderbot")
    old = datetime.datetime.now()
    zero_today = old - datetime.timedelta(days=0, hours=old.hour, minutes=old.minute, seconds=old.second,
                                          microseconds=old.microsecond)
    async for msg in client.iter_messages(dialog, min_id=2110, offset_date=zero_today, reverse=True):
        # user = await client.get_entity(msg.from_id)
        print(" 时间：{} id:{}  消息：{}，   ".format(
            (msg.date + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S"), msg.id, msg.message))
    now = datetime.datetime.now()
    t = now - old
    print(t)


client.loop.run_until_complete(dow())


